// 图片转化为64位字符串
export const ImgTO64BitString = (file) => {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}
// 64位字符串转化为图片src
export const base64ToImageSrc = (base64String) => {
  if (!base64String) {
    return null
  }
  // 将Base64字符串转换为Blob对象
  const blob = b64toBlob(base64String)

  // 创建一个Blob URL
  const imageUrl = URL.createObjectURL(blob)
  return imageUrl
}
// 64位字符串转化为Blob对象
function b64toBlob (b64Data) {
  // 将Base64字符串去除前缀（如果有）
  const contentType = 'image/png'
  const sliceSize = 512
  b64Data = b64Data.split(',')[1]
  // 解码Base64字符串
  const byteCharacters = atob(b64Data)
  const byteArrays = []

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize)
    const byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

  // 将所有的字节数组合并成一个Blob对象
  return new Blob(byteArrays, { type: contentType })
}
